#include "dev_spiflash.h"
#include "context/guicontext.h"

#define   SPI_PORT_W25X           SPI0

#define _SPISSELPORT_		GPIOP
#define _SPISSELPIN_		PIN22


#define _SPI0SCLKPORT_		PORTP
#define _SPI0SCLKPIN_			PIN23

#define _SPI0MOSIPORT_		PORTP
#define _SPI0MOSIPIN_			PIN18

#define _SPI0MISOPORT_		PORTP
#define _SPI0MISOPIN_			PIN19

void SPI_Flash_Init(void)
{
	SPI_InitStructure SPI_initStruct;
	
	GPIO_Init(_SPISSELPORT_, _SPISSELPIN_,  1, 0, 0);				// �������CS
	GPIO_Init(GPIOB, PIN4,  1, 0, 0);				// �������CS

	SPIFlash_CSn_Set;
	SPIFlash_CS2_Set;

	PORT_Init(_SPI0SCLKPORT_, _SPI0SCLKPIN_, FUNMUX1_SPI0_SCLK, 0);
	PORT_Init(_SPI0MOSIPORT_, _SPI0MOSIPIN_, FUNMUX0_SPI0_MOSI, 0);
	PORT_Init(_SPI0MISOPORT_, _SPI0MISOPIN_, FUNMUX1_SPI0_MISO, 1);
	
	SPI_initStruct.clkDiv = SPI_CLKDIV_4;
	SPI_initStruct.FrameFormat = SPI_FORMAT_SPI;
	SPI_initStruct.SampleEdge = SPI_FIRST_EDGE;
	SPI_initStruct.IdleLevel = SPI_LOW_LEVEL;
	SPI_initStruct.WordSize = 8;
	SPI_initStruct.Master = 1;
	SPI_initStruct.RXHFullIEn = 0;
	SPI_initStruct.TXEmptyIEn = 0;
	SPI_initStruct.TXCompleteIEn = 0;
	SPI_Init(SPI_PORT_W25X, &SPI_initStruct);
	SPI_PORT_W25X->CTRL |= 1<<29;
	SPI_Open(SPI_PORT_W25X);
}

uint8_t mysdcard_init(void)
{
	uint8_t resSD;
	
	PORT_Init(PORTB, PIN1, PORTB_PIN1_SD_CLK, 0);
	PORT_Init(PORTB, PIN2, PORTB_PIN2_SD_CMD, 1);
	PORT_Init(PORTB, PIN3, PORTB_PIN3_SD_D0,  1);
	PORT_Init(PORTB, PIN4, PORTB_PIN4_SD_D1,  1);
	PORT_Init(PORTB, PIN5, PORTB_PIN5_SD_D2,  1);
	PORT_Init(PORTB, PIN6, PORTB_PIN6_SD_D3,  1);
	
	resSD = SDIO_Init(50000000);
//	printf("init ssdio============\n");
	
	return resSD;
}